﻿using System;
using System.Linq;
using System.Web.Mvc;
using BLL;
using Model;


namespace Web.Areas.Manager.Controllers
{
    [UserAuthorize]
    public class LeaveApplicationController : Controller
    {
        LeaveApplication_BLL _LeaveApplication_BLL = new LeaveApplication_BLL();
        LeaveApplicationlog_BLL _LeaveApplicationlog_BLL = new LeaveApplicationlog_BLL();
        LeaveApplicationType_BLL _LeaveApplicationType_BLL = new LeaveApplicationType_BLL();
        Sys_Users_BLL _Sys_Users_BLL = new Sys_Users_BLL();

        public virtual ActionResult Index(int? pageIndex, string keyword)
        {
            var model = _LeaveApplication_BLL.Get().Where(a => a.Sys_Users.Id.Equals(new Guid(User.Identity.Name)));
            if (!string.IsNullOrEmpty(keyword))
            {
                //  model = model.Where(a => a.UserName.Contains(keyword));
            }
            return View(model.ToPagedList(pageIndex));
        }


        public virtual ActionResult Details(Guid Id)
        {
            var item = _LeaveApplication_BLL.Get(Id);
            return View(item);
        }

        public virtual ActionResult Edit(Guid? Id)
        {
            ViewBag.LeaveApplicationType = _LeaveApplicationType_BLL.Get();
            if (_LeaveApplicationType_BLL.Get().Count() == 0)
            {
                Response.Write("<script>alert('请先添加请假单类型')</script>");
                Response.End();
            }
           
            var item = _LeaveApplication_BLL.Get(Id);
            return View(item);
        }

        [HttpPost]
        [ValidateInput(false)]
        public virtual ActionResult Edit(Guid? Id, LeaveApplication collection)
        {
            if (!ModelState.IsValid)
            {
                ViewBag.LeaveApplicationType = _LeaveApplicationType_BLL.Get();
                return View(collection);
            }

            var UserId = _Sys_Users_BLL.Get(User.Identity.Name).Id;

            //增加请假单 的默认状态
            VerifyState_BLL _VerifyState_BLL = new VerifyState_BLL();
            var StateId = _VerifyState_BLL.Get().First().Id;

            collection.UserId = UserId;

            collection.StateId = StateId;

            LeaveApplicationLog _LeaveApplicationLog = new LeaveApplicationLog { UserId = UserId, StateId = StateId, Note = "" };
            collection.LeaveApplicationLogs.Add(_LeaveApplicationLog);

            _LeaveApplication_BLL.Save(Id, ref collection);

            return RedirectToAction("Index", RouteData.Values);
        }

        [HttpDelete]
        public virtual ActionResult Delete(Guid Id)
        {
            _LeaveApplication_BLL.Delete(Id);
            return RedirectToAction("Index", RouteData.Values);
        }
    }
}
